package com.example.elmmerchants;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.format.DateUtils;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.Create_Shop.Approved_Page;
import com.example.elmmerchants.Create_Shop.Set_Shop_Data;
import com.example.elmmerchants.Email.SendEmail;
import com.example.elmmerchants.First_Page_Fragment.First_Page;
import com.example.elmmerchants.SQL.Add_Merchant_SQL;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.example.elmmerchants.Sign.Sign_Page;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    boolean is_in_db = false;
    boolean is_approved = false, is_open_auto_get_order = false, is_loading_data = false;
    String user_email, shop_status, qualification_status, legal_status, first_category, second_category;

    private class Data_Thread extends Thread {

        String android_device_id;

        public Data_Thread(String android_device_id) {
            this.android_device_id = android_device_id;
        }

        @Override
        public void run() {
            is_loading_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE phone_id = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, android_device_id);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        if (set.getString("phone_id").equals(android_device_id)) {
                            is_in_db = true;
                            user_email = set.getString("email");
                            first_category = set.getString("first_category");
                            second_category = set.getString("second_category");
                            if (set.getInt("shop_information") == 1) {
                                shop_status = "已录入";
                            }
                            else {
                                shop_status = "待录入";
                            }

                            if (set.getInt("qualification_information") == 1) {
                                qualification_status = "已录入";
                            }
                            else {
                                qualification_status = "待录入";
                            }

                            if (set.getInt("legal_information") == 1) {
                                legal_status = "已录入";
                            }
                            else {
                                legal_status = "待录入";
                            }
                            if (set.getInt("approved") == 1) {
                                is_approved = true;
                            }
                            if (set.getInt("is_open_auto") == 1) {
                                is_open_auto_get_order = true;
                            }
                            else {
                                is_open_auto_get_order = false;
                            }
                            break;
                        }
                    }

                    String sql2 = "SELECT * FROM merchant_shop_full_reduction_activity WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql2);
                    preparedStatement.setString(1, user_email);
                    ResultSet set2 = preparedStatement.executeQuery();
                    while (set2.next()) {
                        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                        Date date = df.parse(set2.getString("activity_end_day"));
                        Date today = new Date();
                        if (set2.getInt("is_auto_postponement") == 1 && date.getTime() + 86400000 < today.getTime()) {
                            String sql3 = "update `elm`.`merchant_shop_full_reduction_activity` set activity_end_day = ? where email = ?";
                            PreparedStatement preparedStatement2 = connection.prepareStatement(sql3);
                            preparedStatement2.setString(1, set_day(set2.getString("activity_end_day")));
                            preparedStatement2.setString(2, user_email);
                            preparedStatement2.executeUpdate();
                        }
                    }

                    String sql3 = "SELECT * FROM merchant_reduce_the_delivery_fee WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql3);
                    preparedStatement.setString(1, user_email);
                    ResultSet set3 = preparedStatement.executeQuery();
                    while (set3.next()) {
                        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                        Date date = df.parse(set3.getString("activity_end_day"));
                        Date today = new Date();
                        if (set3.getInt("is_auto_postponement") == 1 && date.getTime() + 86400000 < today.getTime()) {
                            String sql4 = "update `elm`.`merchant_reduce_the_delivery_fee` set activity_end_day = ? where email = ?";
                            PreparedStatement preparedStatement2 = connection.prepareStatement(sql4);
                            preparedStatement2.setString(1, set_day(set3.getString("activity_end_day")));
                            preparedStatement2.setString(2, user_email);
                            preparedStatement2.executeUpdate();
                        }
                    }

                    String sql4 = "SELECT * FROM merchant_discount_product_page WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql4);
                    preparedStatement.setString(1, user_email);
                    ResultSet set4 = preparedStatement.executeQuery();
                    while (set4.next()) {
                        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                        Date date = df.parse(set4.getString("activity_end_day"));
                        Date today = new Date();
                        if (set4.getInt("is_auto_postponement") == 1 && date.getTime() + 86400000 < today.getTime()) {
                            String sql5 = "update `elm`.`merchant_reduce_the_delivery_fee` set activity_end_day = ? where email = ?";
                            PreparedStatement preparedStatement2 = connection.prepareStatement(sql5);
                            preparedStatement2.setString(1, set_day(set4.getString("activity_end_day")));
                            preparedStatement2.setString(2, user_email);
                            preparedStatement2.executeUpdate();
                        }
                    }

                    String sql5 = "SELECT * FROM merchant_coupon_collect_points_to_return_coupon WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql5);
                    preparedStatement.setString(1, user_email);
                    ResultSet set5 = preparedStatement.executeQuery();
                    while (set5.next()) {
                        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                        Date date = df.parse(set5.getString("activity_end_day"));
                        Date today = new Date();
                        if (date.getTime() + 86400000 < today.getTime()) {
                            String sql6 = "delete from `elm`.`merchant_coupon_collect_points_to_return_coupon` where email = ?";
                            PreparedStatement preparedStatement2 = connection.prepareStatement(sql6);
                            preparedStatement2.setString(1, user_email);
                            preparedStatement2.executeUpdate();
                        }
                    }

                    String sql6 = "SELECT * FROM merchant_coupon_return_coupon_for_placing_an_order WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql6);
                    preparedStatement.setString(1, user_email);
                    ResultSet set6 = preparedStatement.executeQuery();
                    while (set6.next()) {
                        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                        Date date = df.parse(set6.getString("activity_end_day"));
                        Date today = new Date();
                        if (date.getTime() + 86400000 < today.getTime()) {
                            String sql7 = "delete from `elm`.`merchant_coupon_return_coupon_for_placing_an_order` where email = ?";
                            PreparedStatement preparedStatement2 = connection.prepareStatement(sql7);
                            preparedStatement2.setString(1, user_email);
                            preparedStatement2.executeUpdate();
                        }
                    }

                    String sql7 = "SELECT * FROM merchant_new_custom_receive_a_discount WHERE email = ?;";
                    preparedStatement = connection.prepareStatement(sql7);
                    preparedStatement.setString(1, user_email);
                    ResultSet set7 = preparedStatement.executeQuery();
                    while (set7.next()) {
                        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                        Date date = df.parse(set7.getString("activity_end_day"));
                        Date today = new Date();
                        if (set7.getInt("is_auto_postponement") == 1 && date.getTime() + 86400000 < today.getTime()) {
                            String sql8 = "update `elm`.`merchant_new_custom_receive_a_discount` set activity_end_day = ? where email = ?";
                            PreparedStatement preparedStatement2 = connection.prepareStatement(sql8);
                            preparedStatement2.setString(1, set_day(set7.getString("activity_end_day")));
                            preparedStatement2.setString(2, user_email);
                            preparedStatement2.executeUpdate();
                        }
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (is_in_db) {
                        if (is_approved) {
                            Intent intent = new Intent(MainActivity.this, First_Page.class);
                            intent.putExtra("email", user_email);
                            intent.putExtra("is_open_auto_get_order", is_open_auto_get_order);
                            startActivity(intent);
                            finish();
                        }
                        else {
                            if (shop_status.equals("已录入") && qualification_status.equals("已录入") && legal_status.equals("已录入")) {
                                startActivity(new Intent(MainActivity.this, Approved_Page.class));
                                finish();
                            }
                            else {
                                Intent intent = new Intent(MainActivity.this, Set_Shop_Data.class);
                                intent.putExtra("user_email", user_email);
                                intent.putExtra("first_category", first_category);
                                intent.putExtra("second_category", second_category);
                                intent.putExtra("shop_information_status", shop_status);
                                intent.putExtra("qualification_information_status", qualification_status);
                                intent.putExtra("legal_information_status", legal_status);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }
                    else {
                        Intent intent = new Intent(MainActivity.this, Sign_Page.class);
                        intent.putExtra("android_id", android_device_id);
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }
    }

    public String set_day(String end_date) {
        Calendar cld = Calendar.getInstance();
        String date = "";
        String year = "";
        year += end_date.charAt(0);
        year += end_date.charAt(1);
        year += end_date.charAt(2);
        year += end_date.charAt(3);
        String month = "";
        month += end_date.charAt(5);
        month += end_date.charAt(6);
        String day = "";
        day += end_date.charAt(8);
        day += end_date.charAt(9);
        cld.set(Calendar.YEAR, Integer.valueOf(year));
        cld.set(Calendar.MONDAY, Integer.valueOf(month));
        cld.set(Calendar.DATE, Integer.valueOf(day));
        cld.add(Calendar.DATE, 30);
        if (cld.get(cld.MONTH) < 10 && cld.get(cld.DATE) < 10) {
            date = cld.get(cld.YEAR) + "/" + "0" + cld.get(cld.MONTH) + "/" + "0" + cld.get(cld.DATE);
        } else if (cld.get(cld.MONTH) < 10) {
            date = cld.get(cld.YEAR) + "/" + "0" + cld.get(cld.MONTH) + "/" + cld.get(cld.DATE);
        } else if (cld.get(cld.DATE) < 10) {
            date = cld.get(cld.YEAR) + "/" + cld.get(cld.MONTH) + "/" + "0" + cld.get(cld.DATE);
        } else {
            date = cld.get(cld.YEAR) + "/" + cld.get(cld.MONTH) + "/" + cld.get(cld.DATE);
        }
        return date;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String android_device_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        Data_Thread dataThread = new Data_Thread(android_device_id);
        dataThread.start();
    }
}